package cn.wgx.module.sys.service;

import cn.wgx.common.base.IBaseService;
import cn.wgx.common.entity.sys.UserRole;
import cn.wgx.common.security.client.config.entity.LoginAppUser;
import cn.wgx.common.security.util.SysUserUtil;
import cn.wgx.module.sys.mapper.UserRoleMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class UserRoleService extends IBaseService<UserRoleMapper, UserRole> {

    @Transactional
    public int updateRoles(List<UserRole> userRoles, String access_token) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userRoles.get(0).getUser_id());
        baseMapper.delete(queryWrapper);
        Date date = new Date();
        LoginAppUser sysUser = SysUserUtil.getLoginAppUser(access_token);
        int r = 0;
        for (UserRole userRole : userRoles) {
            userRole.setUpdateDate(date);
            userRole.setCreateDate(date);
            if (sysUser != null) {
                userRole.setCreateUserId(sysUser.getUser_id().intValue());
                userRole.setUpdateUserId(sysUser.getUser_id().intValue());
            }
            r += baseMapper.insert(userRole);
        }
        return r;
    }
}
